import React, { useReducer } from 'react'
import ReactDOM from 'react-dom'





function App(props) {
    let
        // reducer函数的state是旧的状态值（还未执行dispatch改变时的）
        reducer = (state, actions) => {
            switch (actions.type) {
                case 'add':
                    // 返回新值，return的新值会直接覆盖整个state
                    return {
                        ...state,
                        age: state.age + actions.num
                    }
                case 'minus':
                    return {
                        ...state,
                        age: state.age - actions.num
                    }
                case 'text':
                    return {
                        ...state,
                        name: actions.name
                    }
                default:
                    return {
                        ...state
                    }
            }
        },
        initialState = { name: 'jam', age: 1000 }
    // 类似于useState的hook，可以在静态组件中管理大量状态
    // state是状态变量，dispatch可以管理所有于该状态有关的事件
    // reducer是规则函数，initialState是state的初始值
    const [state, dispatch] = useReducer(reducer, initialState)
    return (
        <>
            <h1>{state.name}</h1>
            <h2>{state.age}</h2>
            <button onClick={() => { dispatch({ type: 'add', num: 10 }) }}>add10</button>
            <button onClick={() => { dispatch({ type: 'minus', num: 7 }) }}>minus7</button>
            <button onClick={() => { dispatch({type: 'text', name: `${state.name === 'jam' ? 'dad': 'jam'}`}) }}>changeName</button>
        </>
    )
}

ReactDOM.render(<App />, document.getElementById('root'))